package com.dt.common.validation.parser;

import java.lang.reflect.Field;

import com.alibaba.fastjson.JSONObject;
import com.dt.common.validation.annotation.Pattern;
import com.dt.common.validation.definition.PatternDefinition;
import com.dt.common.validation.exception.BuildingException;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.PropertyGetter;

public class PatternDefinitionParser extends DefinitionParser {

	@Override
	public DefaultValidationDefinition parseFromAnnotation(Field field, PropertyGetter propertyGetter) {
		Pattern pattern = field.getAnnotation(Pattern.class);
		if (pattern != null) {
			return build(pattern.exp(), pattern.msg(), pattern.caseSensitive());
		}
		return null;
	}

	@Override
	public DefaultValidationDefinition parseFromJson(JSONObject metaValues) {
		String exp = metaValues.getString("exp");
		if (exp == null || exp.isEmpty()) {
			throw new BuildingException("Pattern exp must defined.");
		}

		boolean caseSensitive = true;
		Boolean caseSensitive_ = metaValues.getBoolean("caseSensitive");
		if (caseSensitive_ != null) {
			caseSensitive = caseSensitive_.booleanValue();
		}

		String msg = this.getMsgDefinition(metaValues, true);

		return build(exp, msg, caseSensitive);
	}

	private DefaultValidationDefinition build(String exp, String msg, boolean caseSensitive) {
		PatternDefinition definition = new PatternDefinition();
		definition.setExp(exp, caseSensitive);
		definition.setRawMsg(msg);
		return definition;
	}

}
